import axios from "axios";
import router from "@/router";
import { ElMessage } from "element-plus";
import { AxiosReqTy } from "@/types/common";

// 设置api接口请求地址HOST TODO 发布时修改如下请求地址即可
export const API_HOST = "http://localhost:3000"
// 设置基础的接口请求地址，一般nginx统一转发
let baseURL: string = API_HOST+"/api"
export const UPLOAD_IMG_URL = baseURL+"/upload"

// 设置开发环境地址
if (import.meta.env.VITE_APP_ENV === 'development') {
    console.log('Development!');
    baseURL = "/api"
}

export const request = axios.create({
  baseURL,
  timeout: 6000, // request timeout
});
// 发起请求之前的拦截器
request.interceptors.request.use(
  (config: AxiosReqTy) => {
    // 如果有token 就携带tokon
    const token = window.localStorage.getItem("accessToken");
    if (token) {
      config.headers.common.Authorization = "Bearer " + token;
    }
    return config;
  },
  (error: any) => Promise.reject(error)
);
// 响应拦截器
request.interceptors.response.use(
  (response: any) => {
    const data = response.data;
    if (data.code === 401) {
      window.localStorage.removeItem("accessToken");
      router.push("/login");
      return;
    }
    if (data.code !== 200) {
      ElMessage({
        message: data.message || data.msg,
        type: "error",
      });
      return;
    }
    return data;
  },
  (error: any) => {
    console.log("err", error);
  }
);
// export default service;
